# -*- coding: utf-8 -*-
import os,sys,re
from ts import *
def _wloginfo(info, end='\n'):
    _msg = tslog() + '\t' + info + end
    print(_msg.strip())
    return _msg

class LogController(object):
    def __init__(self, logfile):
        logpath = os.path.dirname(logfile)
        if not os.path.exists(logpath):
            print(os.system('mkdir -p ' + logpath))
        self.logfile = logfile
        _wloginfo('LogFile:' + self.logfile, end='')

    def write(self, info):
        with open(self.logfile, 'a') as fd:
            _info = info.replace('\r', '')
            while '\n' in _info:
                idx = _info.index('\n')
                line, _info = _info[:idx], _info[idx + 1:]
                fd.write(_wloginfo(line))
            fd.write(_wloginfo(_info))
            fd.flush()

    def writeError(self, einfo=None):
        with open(self.logfile, 'a') as fd:
            if einfo:
                fd.write(_wloginfo(einfo))
            fd.write(_wloginfo("Vmean_output: -1 mv"))
            fd.write(_wloginfo("Vmin_output: -1 mV"))
            fd.write(_wloginfo("Vmax_output: -v mV"))
            fd.write(_wloginfo("PMU_output: -v mV"))
